package com.enqualcomm.kids.activities;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.view.PullRefreshListView;
import com.umeng.fb.FeedbackAgent;
import com.umeng.fb.model.Conversation;
import com.umeng.fb.model.DevReply;
import com.umeng.fb.model.Reply;
import com.umeng.fb.model.UserInfo;

import java.lang.reflect.Constructor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import common.utils.PromptUtil;

public class FeedbackActivity extends BaseActivity {
    private FeedbackAgent agent;
    private Conversation defaultConversation;
    private ReplyListAdapter adapter;
    private PullRefreshListView replyListView;
    EditText userReplyContentEdit;
    private static final String KEY_UMENG_CONTACT_INFO_PLAIN_TEXT = "plain";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        try {
            agent = new FeedbackAgent(this);
            UserInfo info = agent.getUserInfo();
            if (info == null)
                info = new UserInfo();
            Map<String, String> contact = info.getContact();
            if (contact == null)
                contact = new HashMap<String, String>();
            String contact_info = new AppDefault().getUsername();
            contact.put(KEY_UMENG_CONTACT_INFO_PLAIN_TEXT, contact_info);
            info.setContact(contact);
            agent.setUserInfo(info);

            defaultConversation = agent.getDefaultConversation();

            replyListView = (PullRefreshListView) findViewById(R.id.umeng_fb_reply_list);
            replyListView.setCanRefresh(true);
            replyListView.setPullRefreshListener(new PullRefreshListView.PullRefreshListener() {

                @Override
                public void onRefresh() {
                    isUserRefresh = true;
                    sync();
                }

                @Override
                public void onLoadMore() {
                }
            });

            adapter = new ReplyListAdapter(this);
            replyListView.setAdapter(adapter);

            // sync up the conversations on Activity start up.
            sync();

            findViewById((R.id.title_bar_left_iv)).setOnClickListener(
                    new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
            TextView title_bar_name=(TextView) findViewById(R.id.title_bar_title_tv);//标题
            title_bar_name.setText(getString(R.string.about_suggest_tickling));

            TextView title_bar_terminal_name_tv = (TextView) findViewById(R.id.title_bar_terminal_name_tv);
            View title_bar_terminal_icon_iv = findViewById(R.id.title_bar_terminal_icon_iv);
            title_bar_terminal_icon_iv.setVisibility(View.GONE);
            title_bar_terminal_name_tv.setVisibility(View.VISIBLE);
            title_bar_terminal_name_tv.setText(getString(R.string.about_suggest_tickling));

            userReplyContentEdit = (EditText) findViewById(R.id.umeng_fb_reply_content);
            userReplyContentEdit.requestFocus();
            findViewById(R.id.umeng_fb_send).setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            String content = userReplyContentEdit
                                    .getEditableText().toString().trim();
                            if (TextUtils.isEmpty(content))
                                return;

                            userReplyContentEdit.getEditableText().clear();

                            defaultConversation.addUserReply(content);
                            sync();

                            // hide soft input window after sending.
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            if (imm != null)
                                imm.hideSoftInputFromWindow(
                                        userReplyContentEdit.getWindowToken(),
                                        0);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
            this.finish();
        }
    }

    void sync() {
        Conversation.SyncListener listener = new Conversation.SyncListener() {

            @Override
            public void onSendUserReply(List<Reply> replyList) {
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onReceiveDevReply(List<DevReply> replyList) {

                //刷新完成
                String dateStr = getString(R.string.refresh_time)+ new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date());
                if (isUserRefresh) {
                    replyListView.onRefreshComplete(dateStr);
                }else {
                    replyListView.setRefreshTime(dateStr);
                }
                if (replyList!=null) {
                    if (!replyList.isEmpty()) {
                        adapter.notifyDataSetChanged();
                    }else if (isUserRefresh) {
                        PromptUtil.toast(getApplicationContext(),R.string.no_response);
                    }
                }else {
                    PromptUtil.toast(getApplicationContext(),R.string.app_no_connection);
                }
                isUserRefresh = false;
            }
        };
        defaultConversation.sync(listener);
    }
    private boolean isUserRefresh;
    class ReplyListAdapter extends BaseAdapter {
        Context mContext;
        LayoutInflater mInflater;

        public ReplyListAdapter(Context context) {
            this.mContext = context;
            mInflater = LayoutInflater.from(mContext);
        }

        /**
         *
         * @param content
         *            提示用户的内容
         * @return
         */
        private DevReply createInitDevReply(String content) {

            try {
                Class c = DevReply.class;
                Constructor constructor = c.getDeclaredConstructor(new Class[] {
                        String.class, String.class, String.class, String.class,
                        String.class });
                constructor.setAccessible(true);
                DevReply devReply = (DevReply) constructor
                        .newInstance(new Object[] { content, "appkey",
                                "userid", "feedback_id", "user_name" });
                return devReply;
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        public int getCount() {
            List<Reply> replyList = defaultConversation.getReplyList();
            return (replyList == null) ? 1 : replyList.size() + 1;
        }

        /*
         * (non-Javadoc)
         *
         * @see android.widget.Adapter#getView(int, android.view.View,
         * android.view.ViewGroup)
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.umeng_fb_list_item,
                        null);

                holder = new ViewHolder();

                holder.replyDate = (TextView) convertView
                        .findViewById(R.id.umeng_fb_reply_date);

                holder.replyContent = (TextView) convertView
                        .findViewById(R.id.umeng_fb_reply_content);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            Reply reply;
            if (position == 0) {
                // 自定义提示内容
                reply = createInitDevReply(getString(R.string.feedback_init_msg));
            } else {
                reply = defaultConversation.getReplyList().get(position - 1);
            }

            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

            if (reply instanceof DevReply) {
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); // ALIGN_PARENT_RIGHT
                holder.replyContent.setLayoutParams(layoutParams);

                // set bg after layout
                holder.replyContent
                        .setBackgroundResource(R.drawable.chatfrom_bg);
            } else {
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); // ALIGN_PARENT_RIGHT
                // layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
                holder.replyContent.setLayoutParams(layoutParams);
                holder.replyContent
                        .setBackgroundResource(R.drawable.chatto_bg);
            }

            holder.replyDate.setText(SimpleDateFormat.getDateTimeInstance()
                    .format(reply.getDatetime()));
            holder.replyContent.setText(reply.getContent());

            return convertView;
        }

        /*
         * (non-Javadoc)
         *
         * @see android.widget.Adapter#getItem(int)
         */
        @Override
        public Object getItem(int position) {
            return defaultConversation.getReplyList().get(position);
        }

        /*
         * (non-Javadoc)
         *
         * @see android.widget.Adapter#getItemId(int)
         */
        @Override
        public long getItemId(int position) {
            return position;
        }

        class ViewHolder {
            TextView replyDate;
            TextView replyContent;

        }
    }

}
